<template>
  <el-dialog v-model="dialogVisible" :title="title" width="32%">
    <el-form :model="form" label-width="auto" label-position="left">
      <el-form-item label="邮箱">
        <el-input
          v-model="form.email"
          autocomplete="off"
          placeholder="xxx@qq.com"
        />
      </el-form-item>
      <el-form-item label="密码">
        <el-input
          v-model="form.password"
          type="password"
          show-password
        ></el-input>
      </el-form-item>
      <template v-if="loginType !== 1">
        <el-form-item label="验证码">
          <el-input v-model="form.password" />
        </el-form-item>
      </template>
    </el-form>
    <el-checkbox v-model="agreeAccord">我已阅读并同意论坛用户协议</el-checkbox>
    <section style="height: 32px; line-height: 32px;padding-bottom:2rem">
      <el-button type="primary" @click="login" style="width: 60%">
        登录</el-button
      >
    </section>
  </el-dialog>
</template>

<script setup>
import { inject, reactive, ref, watch } from "vue";
import request from "../../../utils/request";
import { ElMessage } from "element-plus";
const dialogVisible = inject("openDialog", false);
let loginType = ref(1);
const urls = [
  "https://mockapi.eolink.com/SHQdMWnc0600b265c0d20410ed7c36e0eec1dc8fe7e5087/user/register?responseId=1201978",
  "https://mockapi.eolink.com/SHQdMWnc0600b265c0d20410ed7c36e0eec1dc8fe7e5087/user/login?responseId=1201977",
  "https://mockapi.eolink.com/SHQdMWnc0600b265c0d20410ed7c36e0eec1dc8fe7e5087/user/update?responseId=1201979",
];
watch(dialogVisible, () => {
  loginType.value = 1;
  title.value = "登录论坛";
});
let title = ref("登录论坛");
let agreeAccord = ref(false);
let form = reactive({
  email: "",
  password: "",
  code: "",
});
const emit = defineEmits(["loginSuccess"]);
const register = (type) => {
  if (type) {
    (title.value = "修改密码"), (loginType.value = 2);
  } else if (loginType.value == 1) {
    title.value = "注册账户";
    loginType.value = 0;
  } else {
    (title.value = "登录账户"), (loginType.value = 1);
  }
};
function login() {
  if (!agreeAccord.value) {
    ElMessage({
      message: "请阅读并同意用户协议",
      type: "warning",
    });
    return;
  }
  request(urls[loginType.value], { ...form }, 1).then((res) => {
    console.log(res);
    localStorage.setItem("Authorization", res.token);
    localStorage.setItem("userInfo", JSON.stringify(res.userInfo));
    ElMessage({
      message: "登录成功，欢迎",
      type: "success",
    });
    dialogVisible.value = false;
    emit('loginSuccess',res.userInfo)
  });
}
</script>
<style>
.el-dialog {
  min-width: 35rem;
  border-radius: 20px;
}
.el-dialog__header {
  height: 40px;
  line-height: 40px;
  padding-bottom: 0;
}
.el-dialog__body {
  padding-top: 20px;
  padding-bottom: 0;
}
</style>
<style scoped lang='less'>
.footer {
  margin-top: 1rem;
  height: 30px;
  line-height: 30px;
  display: flex;
  justify-content: flex-end;
  color: red;
  cursor: pointer;
  section {
    margin-left: 2rem;
  }
}
</style>